package com.yxt.qmgf.shop.ctrl;

import cn.hutool.extra.spring.SpringUtil;
import com.yxt.qmgf.common.ClientSession;
import com.yxt.qmgf.common.view.CdzAlert;
import com.yxt.qmgf.shop.dao.ShopDao;
import com.yxt.qmgf.shop.vo.entity;
import com.yxt.qmgf.userinfo.dao.UserInfoDao;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

@Controller
public class ShopController implements Initializable {

    private static final Logger logger = LoggerFactory.getLogger(ShopController.class);

    @FXML
    private TableView<entity> tableView;
    @FXML
    private TableColumn<entity, Integer> idColumn;
    @FXML
    private TableColumn<entity, String> nameColumn;
    @FXML
    private TableColumn<entity, String> gongnengColumn;
    @FXML
    private TableColumn<entity, String> priceColumn;
    @FXML
    private TableColumn<entity, Integer> haveColumn;
    @FXML
    private TableColumn<entity, Integer> UidColumn;
    @FXML
    private TableColumn<entity, String> actionColumn;
    @FXML
    private TableColumn<entity, Void> buyColumn;
    @FXML
    private TableColumn<entity, Void> useColumn;

    @FXML
    private Button addProductButton;
    private ObjectProperty<UserInfoVO> currentUser = new SimpleObjectProperty<>();
    private ObservableList<entity> productList = FXCollections.observableArrayList();
    private BooleanBinding addButtonVisibleBinding;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 获取当前用户信息
        UserInfoVO user = (UserInfoVO) ClientSession.getAttribute("user_info");
        currentUser.set(user);

        // 设置新增按钮的可见性绑定
        addButtonVisibleBinding = createAddButtonVisibleBinding();
        addProductButton.visibleProperty().bind(addButtonVisibleBinding);

        // 初始化表格列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        gongnengColumn.setCellValueFactory(new PropertyValueFactory<>("gongneng"));
        priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
        haveColumn.setCellValueFactory(new PropertyValueFactory<>("have"));
        UidColumn.setCellValueFactory(new PropertyValueFactory<>("Uid"));
        // 设置操作列
        setActionColumn();
        setBuyColumn();
        setUseColumn();

        // 加载商品数据
        loadProducts();
    }

    private BooleanBinding createAddButtonVisibleBinding() {
        return Bindings.createBooleanBinding(() -> currentUser.get() != null && "1".equals(currentUser.get().getCode()), currentUser);
    }

    private void setActionColumn() {
        Callback<TableColumn<entity, String>, TableCell<entity, String>> cellFactory = param -> new TableCell<>() {
            private final Button editButton = new Button("编辑");
            private final Button deleteButton = new Button("删除");
            private final HBox hbox = new HBox(5, editButton, deleteButton);

            {
                editButton.setOnAction(event -> {
                    entity product = getTableView().getItems().get(getIndex());
                    openEditDialog(product);
                });

                deleteButton.setOnAction(event -> {
                    entity product = getTableView().getItems().get(getIndex());
                    deleteProduct(product);
                });

                currentUser.addListener((observable, oldUser, newUser) -> {
                    boolean isAdmin = newUser != null && "1".equals(newUser.getCode());
                    hbox.setVisible(isAdmin);
                    hbox.setManaged(isAdmin);
                });
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(currentUser.get() != null && "1".equals(currentUser.get().getCode())? hbox : null);
                }
            }
        };
        actionColumn.setCellFactory(cellFactory);
    }

    private void setBuyColumn() {
        Callback<TableColumn<entity, Void>, TableCell<entity, Void>> cellFactory = param -> new TableCell<>() {
            private final Button buyButton = new Button("购买");

            {
                buyButton.setOnAction(event -> {
                    entity product = getTableView().getItems().get(getIndex());
                    buyProduct(product);
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(buyButton);
                }
            }
        };
        buyColumn.setCellFactory(cellFactory);
    }

    private void setUseColumn() {
        Callback<TableColumn<entity, Void>, TableCell<entity, Void>> cellFactory = param -> new TableCell<>() {
            private final Button useButton = new Button("使用");

            {
                useButton.setOnAction(event -> {
                    entity product = getTableView().getItems().get(getIndex());
                    if (product.getHave() > 0) {
                        useProduct(product);
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    entity product = getTableView().getItems().get(getIndex());
                    setGraphic(product.getHave() > 0? useButton : null);
                }
            }
        };
        useColumn.setCellFactory(cellFactory);
    }

    private void loadProducts() {
        try {
            UserInfoVO user = currentUser.get();
            String Uid = user.getUid();
            SpringUtil.getBean(ShopDao.class).updateUidForAll(Uid);

            productList.clear();
            List<entity> products = SpringUtil.getBean(ShopDao.class).selectList(null);
            productList.addAll(products);
            tableView.setItems(productList);
        } catch (Exception e) {
            logger.error("加载商品数据失败", e);
            new CdzAlert(Alert.AlertType.ERROR, "加载商品数据失败").show();
        }
    }

    @FXML
    private void addProduct() {
        if (isAdmin()) {
            entity newProduct = new entity();
            openEditDialog(newProduct);
        } else {
            logger.warn("非管理员用户尝试添加商品");
            new CdzAlert(Alert.AlertType.WARNING, "只有管理员可以添加商品").show();
        }
    }

    private boolean isAdmin() {
        UserInfoVO user = currentUser.get();
        return user != null && "1".equals(user.getCode());
    }

    private void openEditDialog(entity product) {
        try {
            // 加载编辑窗口的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/shop/ProductEdit.fxml"));
            Parent root = loader.load();

            // 获取编辑窗口控制器
            ProductEditController controller = loader.getController();
            controller.setProduct(product); // 传递要编辑的商品对象

            // 创建并显示对话框
            Stage dialogStage = new Stage();
            dialogStage.setTitle("编辑商品");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            dialogStage.initOwner(tableView.getScene().getWindow());
            dialogStage.setScene(new Scene(root));
            dialogStage.showAndWait();

            // 刷新商品列表
            loadProducts();
        } catch (IOException e) {
            logger.error("打开编辑窗口失败", e);
            new CdzAlert(Alert.AlertType.ERROR, "打开编辑窗口失败").show();
        }
    }

    private void deleteProduct(entity product) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("您确定要删除此商品吗？");
        alert.setContentText("商品名称: " + product.getName() + ", 商品ID: " + product.getId());

        if (alert.showAndWait().orElse(ButtonType.CANCEL) == ButtonType.OK) {
            try {
                SpringUtil.getBean(ShopDao.class).Delete(product.getId());
                loadProducts();
            } catch (Exception e) {
                logger.error("删除商品失败", e);
                new CdzAlert(Alert.AlertType.ERROR, "删除商品失败").show();
            }
        }
    }

    private void buyProduct(entity product) {
        UserInfoVO user = currentUser.get();
        if (user == null) {
            new CdzAlert(Alert.AlertType.WARNING, "请先登录").show();
            return;
        }

        try {
            int userScore = Integer.parseInt(user.getScore());
            int productPrice = Integer.parseInt(product.getPrice());

            if (userScore >= productPrice) {
                user.setScore(String.valueOf(userScore - productPrice));
                SpringUtil.getBean(UserInfoDao.class).UpdateByVo(user);
                product.setHave(product.getHave() + 1);
                SpringUtil.getBean(ShopDao.class).Update(product);
                loadProducts();
                new CdzAlert(Alert.AlertType.INFORMATION, "购买成功！").show();
            } else {
                new CdzAlert(Alert.AlertType.WARNING, "积分不足，无法购买！").show();
            }
        } catch (NumberFormatException e) {
            logger.error("积分或价格格式错误", e);
            new CdzAlert(Alert.AlertType.ERROR, "积分或价格格式错误！").show();
        } catch (Exception e) {
            logger.error("购买商品失败", e);
            new CdzAlert(Alert.AlertType.ERROR, "购买商品失败").show();
        }
    }

    private void useProduct(entity product) {
        if (product.getHave() > 0) {
            product.setHave(product.getHave() - 1);
            try {
                SpringUtil.getBean(ShopDao.class).Update(product);
                loadProducts();
                new CdzAlert(Alert.AlertType.INFORMATION, "您已使用" + product.getName()).show();
            } catch (Exception e) {
                logger.error("使用商品失败", e);
                new CdzAlert(Alert.AlertType.ERROR, "使用商品失败").show();
            }
        } else {
            new CdzAlert(Alert.AlertType.WARNING, "您没有此商品，无法使用！").show();
        }
    }


}